#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include "notifier.h"
#include "benchapi.h"

static char incoming_pipe_buffer[4096]  =   {'\0'};
static int  incoming_pipe_handles[2]    =   {-1, -1};
static int  worker_pipe_handles[2]      =   {-1, -1};

int incoming_pipe_create(void)
{
	int ret_code = -1;

    if (pipe (incoming_pipe_handles) == -1)
		goto create_pipe_exit;

    fcntl(incoming_pipe_handles[0], F_SETFL, O_NONBLOCK | O_RDONLY);
	fcntl(incoming_pipe_handles[1], F_SETFL, O_NONBLOCK | O_WRONLY);

	fcntl(incoming_pipe_handles[0], F_SETFD, FD_CLOEXEC);
	fcntl(incoming_pipe_handles[1], F_SETFD, FD_CLOEXEC);
    
	return 0;
    
create_pipe_exit:	
    
	BOOT_LOG (ret_code, "create incoming notify pipe");
}

int worker_pipe_create(void)
{
	int ret_code = -1;

    if (pipe (worker_pipe_handles) == -1)
		goto create_pipe_exit;

	fcntl(worker_pipe_handles[0], F_SETFD, FD_CLOEXEC);
	fcntl(worker_pipe_handles[1], F_SETFD, FD_CLOEXEC);
    
	return 0;
    
create_pipe_exit:	
    
	BOOT_LOG (ret_code, "create worker notify pipe");
}

void incoming_wr_pipe_close (void) {
	close (incoming_pipe_handles[1]);
}

void worker_wr_pipe_close (void) {
	close (worker_pipe_handles[1]);
}

void incoming_rd_pipe_close (void) {
	close (incoming_pipe_handles[0]);
}

void worker_rd_pipe_close (void) {
	close (worker_pipe_handles[0]);
}

int incoming_pipe_rd_fd (void) {
	return incoming_pipe_handles[0];
}

int worker_pipe_rd_fd (void) {
	return worker_pipe_handles[0];
}

void incoming_read_pipe (void) {
	read (incoming_pipe_handles[0], incoming_pipe_buffer, sizeof(incoming_pipe_buffer));
}

void worker_read_pipe (void) {
    char notify_chr;
	read (worker_pipe_handles[0], &notify_chr, 1);
}

void incoming_write_pipe (void) {
	char notify_chr;
	write (incoming_pipe_handles[1], &notify_chr, 1);
}

void worker_write_pipe (void) {
	char notify_chr;
	write (worker_pipe_handles[1], &notify_chr, 1);
}

